package cn.zhentao.speechai.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Base64;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;

@Service
public class VoiceRecognizeService {
    
    private static final Logger logger = LoggerFactory.getLogger(VoiceRecognizeService.class);
    
    // 百度语音识别配置
    @Value("${voice.baidu.api-key:}")
    private String baiduApiKey;
    
    @Value("${voice.baidu.secret-key:}")
    private String baiduSecretKey;
    
    @Value("${voice.baidu.app-id:}")
    private String baiduAppId;
    
    @Value("${voice.baidu.max-duration:60000}")
    private long maxDuration;
    
    private String accessToken;
    
    @PostConstruct
    public void init() {
        logger.info("语音识别服务初始化完成");
        logger.info("百度配置 - AppID: {}", baiduAppId);
        logger.info("百度配置 - API Key: {}***", baiduApiKey.length() > 4 ? baiduApiKey.substring(0, 4) : "未配置");
        logger.info("百度配置 - Secret Key: {}***", baiduSecretKey.length() > 4 ? baiduSecretKey.substring(0, 4) : "未配置");
    }
    
    /**
     * 识别音频文件
     */
    public Map<String, Object> recognizeAudio(MultipartFile audioFile, String format, int sampleRate) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 检查文件大小
            if (audioFile.getSize() > maxDuration * 1000) {
                result.put("success", false);
                result.put("message", "音频文件过大");
                return result;
            }
            
            // 检查百度API配置
            if (baiduApiKey.isEmpty() || baiduSecretKey.isEmpty() || baiduAppId.isEmpty()) {
                logger.warn("百度API配置不完整，使用模拟识别");
                return generateMockResult();
            }
            
            // 获取访问令牌
            if (accessToken == null || accessToken.isEmpty()) {
                if (!getAccessToken()) {
                    logger.warn("获取百度Access Token失败，使用模拟识别");
                    return generateMockResult();
                }
            }
            
            // 调用百度语音识别API
            return callBaiduVoiceAPI(audioFile, format, sampleRate);
            
        } catch (Exception e) {
            logger.error("语音识别处理异常", e);
            result.put("success", false);
            result.put("message", "语音识别处理异常: " + e.getMessage());
            return result;
        }
    }
    
    /**
     * 获取百度Access Token
     */
    private boolean getAccessToken() {
        try {
            String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + 
                        baiduApiKey + "&client_secret=" + baiduSecretKey;
            
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            
            logger.info("百度Token API响应 - 状态码: {}, 响应: {}", response.getStatusCodeValue(), response.getBody());
            
            if (response.getStatusCodeValue() == 200) {
                // 解析响应获取access_token
                String responseBody = response.getBody();
                if (responseBody != null && responseBody.contains("\"access_token\"")) {
                    // 简单解析JSON获取access_token
                    String[] parts = responseBody.split("\"access_token\":\"");
                    if (parts.length > 1) {
                        accessToken = parts[1].split("\"")[0];
                        logger.info("成功获取百度Access Token: {}***", accessToken.substring(0, Math.min(10, accessToken.length())));
                        return true;
                    }
                }
            }
            
            logger.error("获取百度Access Token失败,状态码:{},响应:{}", response.getStatusCodeValue(), response.getBody());
            return false;
            
        } catch (Exception e) {
            logger.error("获取百度Access Token异常", e);
            return false;
        }
    }
    
    /**
     * 调用百度语音识别API
     */
    private Map<String, Object> callBaiduVoiceAPI(MultipartFile audioFile, String format, int sampleRate) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            String url = "https://vop.baidu.com/server_api";
            
            // 读取音频文件并转换为Base64
            byte[] audioBytes = audioFile.getBytes();
            String audioBase64 = Base64.getEncoder().encodeToString(audioBytes);
            
            // 构建请求体 - 使用正确的百度API格式
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("format", format);
            requestBody.put("rate", sampleRate);
            requestBody.put("channel", 1);
            // 使用符合百度API要求的cuid格式：简单的数字字符串，长度不超过60字符
            String cuid = baiduAppId + String.valueOf(System.currentTimeMillis()).substring(8) + String.format("%04d", (int)(Math.random() * 10000));
            requestBody.put("cuid", cuid);
            requestBody.put("speech", audioBase64);
            requestBody.put("len", audioBytes.length);
            
            logger.info("百度API请求参数: format={}, rate={}, len={}, cuid={}", format, sampleRate, audioBytes.length, cuid);
            logger.info("使用的Access Token: {}", accessToken);
            
            // 构建完整的URL，包含access_token参数
            String fullUrl = url + "?access_token=" + accessToken;
            
            // 使用RestTemplate发送POST请求
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json");
            
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            ResponseEntity<String> response = restTemplate.exchange(fullUrl, HttpMethod.POST, entity, String.class);
            
            logger.info("百度API响应 - 状态码: {}, 响应: {}", response.getStatusCodeValue(), response.getBody());
            
            if (response.getStatusCodeValue() == 200) {
                // 解析百度API响应
                String responseBody = response.getBody();
                if (responseBody != null && responseBody.contains("\"err_no\":0")) {
                    // 识别成功
                    String[] parts = responseBody.split("\"result\":\\[");
                    if (parts.length > 1) {
                        String resultPart = parts[1].split("\\]")[0];
                        String recognizedText = resultPart.replaceAll("\"", "").trim();
                        
                        result.put("success", true);
                        result.put("text", recognizedText);
                        result.put("message", "识别成功");
                        
                        logger.info("语音识别成功: {}", recognizedText);
                        return result;
                    }
                } else {
                    // 识别失败
                    result.put("success", false);
                    result.put("message", "百度API识别失败: " + responseBody);
                    return result;
                }
            }
            
            result.put("success", false);
            result.put("message", "百度API请求失败，状态码: " + response.getStatusCodeValue());
            return result;
            
        } catch (Exception e) {
            logger.error("调用百度语音识别API异常", e);
            result.put("success", false);
            result.put("message", "调用百度API异常: " + e.getMessage());
            return result;
        }
    }
    
    /**
     * 生成模拟识别结果
     */
    private Map<String, Object> generateMockResult() {
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("text", "你好，请帮我解答一个问题");
        result.put("message", "模拟识别成功");
        return result;
    }
}